<script setup>
import {onMounted, reactive, ref} from "vue";
import {
  addBookService,
  deleteBookBatchService,
  deleteBookService,
  getBookListService,
  updateBookService
} from "@/api/book.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";

const data = reactive({
  user: {},
  name: '',
  author: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  dialogVisible: false,
  dialogTitle: '',
  bookForm: {},
  selectedRows: [],
})
const formRef = ref()

const rules = {
  name: [
    {required: true, message: '图书名称不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '名称长度在 2 ~ 50 位之间', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (!value && value !== 0) {
          callback(new Error('请输入有效的价格'));
        } else if (value < 0) {
          callback(new Error('价格不能为负数'));
        } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
          callback(new Error('价格最多保留两位小数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  author: [
    {required: true, message: '作者名不能为空', trigger: 'blur'},
    {min: 2, max: 30, message: '作者名长度在 2 ~ 50 位之间', trigger: 'blur'}
  ],
  quantity: [
    {required: true, message: '请输入数量', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数'));
        } else if (value < 0) {
          callback(new Error('数量不能为负数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  publisher: [
    {required: true, message: '出版社不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '出版社名称长度在 2 ~ 50 位之间', trigger: 'blur'}
  ]
};


const userData = JSON.parse(localStorage.getItem('user'))
const parsedUser = (typeof userData === 'string') ? JSON.parse(userData) : userData || {};
data.user = parsedUser;


// 表格行数据
const handleSelectionChange = (val) => {
  data.selectedRows = val
}

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  data.pageSize = newSize;
  ArticleList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  data.pageNum = newPage;
  ArticleList();
};


// 图书列表
const BookList = async () => {
  const res = await getBookListService({
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    name: data.name,
    author: data.author
  });
  if (res.data.code === '200') {
    data.tableData = res.data.data.list
    data.total = res.data.data.total;
  }
}

onMounted(async () => {
  await BookList()
})

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

// 返回状态文本
// const getStatusText = (status) => {
//   const statusMap = {
//     0: '待审核',
//     1: '已通过',
//     2: '已拒绝'
//   };
//   return statusMap[status] || '未知状态';
// };

const handleOpenDialog = (row) => {
  if (row.id) {
    data.dialogTitle = '修改图书'
    data.dialogVisible = true
    data.bookForm = row
  } else {
    data.dialogTitle = '新增图书'
    data.dialogVisible = true
    data.bookForm = {}
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isValidFormat = /\.(jpg|jpeg|png)$/i.test(file.name);
  const isValidSize = file.size / 1024 / 1024 < 2;
  if (!isValidFormat) {
    ElMessage.error('只能上传 JPG/JPEG/PNG 格式的图片');
    return false;
  }
  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }
  return true;
};

// 头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === "200") {
    ElMessage.success("上传成功");
    data.bookForm.cover = response.data;
    BookList();
  } else {
    ElMessage.error(response.message);
  }
};

const handleSaveBook = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (data.bookForm.cover) {
        if (data.bookForm.id) {
          const res = await updateBookService(data.bookForm);
          if (res.data.code === '200') {
            ElMessage.success('修改成功');
            data.dialogVisible = false
            await BookList();
          }
        } else {
          const res = await addBookService(data.bookForm);
          if (res.data.code === '200') {
            ElMessage.success("新增成功")
            data.dialogVisible = false
            await BookList();
          }
        }
      } else {
        ElMessage.error("请上传封面")
      }

    } else {
      ElMessage.error('请填写完整信息');
      return false;
    }
  });
}

// 批量删除图书
const handleBookDeleteBatch = async () => {
  if (!data.selectedRows || data.selectedRows.length === 0) {
    ElMessage.warning("请先选择要删除的图书");
    return;
  }
  const ids = data.selectedRows.map(item => item.id)
  ElMessageBox.confirm(
      '当前操作将永久删除选中的图书，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteBookBatchService(ids)
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await BookList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    ArticleList()
    ElMessage.info('取消删除');
  });
}


// 删除图书
const handleBookDelete = async (id) => {
  ElMessageBox.confirm(
      '当前操作将永久删除当前图书，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteBookService(id)
    if (res.data.code === "200") {
      ElMessage.success("删除成功")
      await BookList()
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

const refresh = () => {
  data.name = ''
  data.author = ''
  BookList()
}
</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="data.name" clearable style="width: 240px; margin-right: 20px" placeholder="请输入图书名称"/>
      <el-input v-model="data.author" clearable style="width: 240px" placeholder="请输入作者名"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="BookList">查询</el-button>
      <el-button type="warning" icon="refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" style="margin-left: 0" icon="DocumentAdd"
                 @click="handleOpenDialog">新增图书
      </el-button>
      <el-button type="danger" style="margin-left: 0" icon="Delete"
                 @click="handleBookDeleteBatch">批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="data.tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column prop="cover" align="center" label="封面" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.cover" :src="scope.row.cover" fit="cover"
                      :preview-src-list="[scope.row.cover]" :preview-teleported="true"
                      style="width: 50px; height: 50px; border-radius: 50%">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="名称"/>
        <el-table-column prop="price" align="center" label="价格"/>
        <el-table-column prop="author" align="center" label="作者"/>
        <el-table-column prop="quantity" align="center" label="数量"/>
        <el-table-column prop="publisher" align="center" label="出版社"/>
        <el-table-column prop="publishTime" align="center" label="出版日期">
          <template #default="scope">
            <el-text type="info">{{ formatDate(scope.row.publishTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="handleOpenDialog(scope.row)" icon="Edit">修改</el-button>
            <el-button type="danger" icon="Delete" @click="handleBookDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 新增 / 修改 -->
  <el-dialog v-model="data.dialogVisible" :title="data.dialogTitle" align-center width="500" destroy-on-close>
    <el-form :model="data.bookForm" :rules="rules" ref="formRef" label-width="80px"
             style="padding: 0 50px 0 0">
      <el-form-item class="el-form-item-avatar">
        <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:9090/api/file/upload"
            :show-file-list="false"
            :headers="{ Authorization: data.user.token }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="data.bookForm.cover" :src="data.bookForm.cover" alt="图像无法加载"
               style="width: 120px; height: 120px"
               class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名称" prop="name" class="el-form-item">
        <el-input v-model="data.bookForm.name" placeholder="图书名称"/>
      </el-form-item>
      <el-form-item label="价格" prop="price" class="el-form-item">
        <el-input-number v-model="data.bookForm.price" :min="0" :step="0.01" step-strictly style="width: 100%"/>
      </el-form-item>
      <el-form-item label="作者" prop="author" class="el-form-item">
        <el-input v-model="data.bookForm.author" placeholder="图书作者"/>
      </el-form-item>
      <el-form-item label="数量" prop="quantity" class="el-form-item">
        <el-input-number v-model="data.bookForm.quantity" :min="0" :step="1" step-strictly style="width: 100%"/>
      </el-form-item>
      <el-form-item label="出版社" prop="publisher" class="el-form-item">
        <el-input v-model="data.bookForm.publisher" placeholder="出版社"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="margin: 10px 0 ">
        <el-button @click="data.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveBook">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.avatar-uploader .el-upload) {
  width: 120px;
  height: 120px;
  border: 2px dashed var(--el-border-color);
  cursor: pointer;
  display: flex;
  border-radius: 20px;
  align-items: center;
  justify-content: center;
  position: relative;
  left: 90px;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin: 0 auto;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  padding: 5px;
  cursor: pointer;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.button {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.button-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

:deep() .el-form-item {
  margin-top: 25px;
}
</style>